package probe.sound.code;

import java.io.InputStream;
import java.io.RandomAccessFile;

import probe.sound.resources.Resources;

public class CreateWaveBeep1000Hz {
  
  public static void main(String[] args) throws Exception {
    System.out.println( "1000Hz beeping..." );
    
    double sampleRate = 48000;
    double beepDelay = 2;//delay in secods
    double A = 0.9;//=0...1 - loudness
    double Hz = 1000;
    
    RandomAccessFile f = new RandomAccessFile( "/tmp/beep1000Hz.wav", "rw" );
    
    f.seek( 44 );
    int dataSize = 0;
    
    byte[] buf = new byte[1024];
    
    int iCount = buf.length / 4;
    
    U: for (int u = 0; true; u++) {
      int bufferFilledOn = buf.length;
      I: for (int i = 0; i < iCount; i++) {
        
        int iSample = u * iCount + i;
        
        double t = ((double)iSample) / sampleRate; //time in seconds
        
        if (t > beepDelay) {
          bufferFilledOn = i * 4;
          break I;
        }
        
        double x = A * Math.sin( Hz * (2 * Math.PI) * t );
        
        int left = Util.toSignedWord( x );
        int right = Util.toSignedWord( x );
        
        Util.writeWord( buf, 4 * i + 0, true, left );
        Util.writeWord( buf, 4 * i + 2, true, right );
      }
      
      if (bufferFilledOn == 0) break U;
      
      f.write( buf, 0, bufferFilledOn );
      dataSize += bufferFilledOn;
      
    }
    
    f.seek( 0 );
    
    InputStream in = Resources.class.getResourceAsStream( "wave.header.bin" );
    byte header[] = new byte[44];
    int readToHeader = in.read( header );
    in.close();
    if (readToHeader != header.length) {
      f.close();
      throw new RuntimeException( "Left header" );
    }
    
    Util.writeInt4( header, 40, true, dataSize );
    
    f.write( header );
    
    f.close();
    
    System.out.println( "Complete" );
  }
  
}
